import React from 'react';
import TodoItem from './TodoItem'
class TodoList extends React.Component {
    constructor(props) {
        super(props) //固定写法
        this.state = {
            inputValue: '',
            list: []
        }
        this.handleInputChange = this.handleInputChange.bind(this)
        this.handleDelete = this.handleDelete.bind(this)
    }
    render() {
        return <>
            <label htmlFor='insertArea'>输入</label>
            <input id='insertArea'
                value={this.state.inputValue}
                onChange={this.handleInputChange}
                ref={(input) => { this.input = input }}></input>
            <button onClick={this.handleSubmitClick}>提交</button>
            <ul ref={(ul) => { this.ul = ul }}>
                {this.getTodoItem()}
            </ul>
            <p>不需要自动转义，输入标签测试</p>
            <ul>
                {this.state.list.map((item, index) => {
                    return (<li key={index}
                        onClick={() => this.handleDelete(index)}
                        dangerouslySetInnerHTML={{ __html: item }}>
                    </li>)
                })}
            </ul>
        </>
    }

    handleInputChange(e) {
        // this.setState(() => {
        //     return { inputValue: e.target.value }
        // })
        // const value = e.target.value //为什么要提取出来，因为异步
        const value = this.input.value
        this.setState(() => ({
            inputValue: value
        }))
    }
    handleSubmitClick = () => {
        // this.setState({
        //     list: [...this.state.list, this.state.inputValue],
        //     inputValue: ''
        // })
        this.setState((preState) => ({
            list: [...preState.list, preState.inputValue],
            inputValue: ''
        }), () => {
            const length = this.ul.querySelectorAll('div').length
            console.log(length)
        })

    }
    handleDelete(index) {
        this.setState((preState) => {
            const list = [...preState.list];
            list.splice(index, 1)
            return list
        })
    }
    getTodoItem() {
        return this.state.list.map((item, index) => {
            // return (<li key={index} onClick={() => this.handleDelete(index)}>{item}</li>)
            return <TodoItem key={index}
                item={item}
                index={index}
                deleteItem={this.handleDelete.bind(this)} /> //传递绑定的是class的this
        })
    }
}

export default TodoList